const WXAPI = require('../../wxapi/main')
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    phone: '',
    msg: false,
    checkValue: 1,
    check: false,
    isShowAgree: false,
    dialog2: false,
    show2: false,
  },

  agree() {
    this.setData({
      dialog2: false,
      check: true,
    });
    var that = this;
    setTimeout(function(){
      that.setData({      
        show2: false,       
      });
    }, 400);
  },
  close() {
    this.setData({
      dialog2: false,
    });

    var that = this;
    setTimeout(function(){
      that.setData({      
        show2: false,       
      });
    }, 400);
  },

  open2() {
    this.setData({
      dialog2: true,
      show2: true,
    });

    const promise1 = new Promise((resolve, reject) => {
      wx.createSelectorQuery().select('#js_btn1_1')
        .boundingClientRect((rect) => {
          resolve(rect.height);
        })
        .exec();
    });
    const promise2 = new Promise((resolve, reject) => {
      wx.createSelectorQuery().select('#js_btn1_2')
        .boundingClientRect((rect) => {
          resolve(rect.height);
        })
        .exec();
    });
    Promise.all([promise1, promise2]).then((values) => {
      if (values[0] != values[1]) {
        this.setData({ wrap: true });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
  },

  checkboxChange(e) {
    if (e.detail.value.includes('1')) {
      this.setData({
        check: true,
      });
    } else {
      this.setData({
        check: false,
      });
    }
  },

  getPhoneNumber: function (e) {
    let that = this
    console.log('获取手机号的动态令牌', e.detail.code)  // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno)  // 错误码（失败时返回）
   
    wx.login({
      success: function(loginRes) {
        console.log('wx.login ret ', loginRes)
        if (loginRes.code) {
          wx.request({
            url: app.globalApi.loginUrl,
            data: {
              code: loginRes.code
            },
            success: function(res) {
              console.log('login success', res);         
              let resData = res.data     
              if (resData.result == 0) {
                let _resData =  resData.data
                // app.globalData.partUserInfo = _resData;
                let {session_key, skey, openid} = _resData
                // 调用手机号
                let _inviteCode = wx.getStorageSync('inviteCode')?wx.getStorageSync('inviteCode'):''
                console.log('_inviteCode ', _inviteCode)
                let _initPhonePost = {code:e.detail.code, sessionKey:session_key, skey, openid, inviteCode: _inviteCode}
                console.log('request post ', _initPhonePost)
                WXAPI.initPhone(_initPhonePost).then(res2 => { // 服务端获取手机号
                  console.log('init phone ret ', res2)
                  if (res2.result == 0) {
                    wx.setStorageSync('partUserInfo', res2.data)
                    wx.setStorageSync('loginFlag', res2.data.skey);                   
                    if (_inviteCode) {
                      // 如果有推荐的话，增加积分1
                      WXAPI.increaseScore({inviteCode: _inviteCode}).then(res3 => {
                        console.log('increaseScore ', res3)
                      })
                    }
                    // 回到原来的地方放
                    app.navigateToLogin = false
                    wx.navigateBack();
                  }
                })              
              } else {
                app.showInfo(res.errmsg)
              }
            },
          })
        } else {
          app.showInfo(res.errmsg)
        }
      },
      fail: function() {
        // 获取临时code失败
        that.showInfo('登录失败')
        console.log('调用wx.login获取code失败');
      }
    })
  },

  go_vcode: function(e) {
    wx.navigateTo({
      url: '/pages/authorize-vcode/index',
    })
  },

  showInfo: function() {
    this.setData({
      isShowAgree: true
    })
  },
  closeAgree: function() {
    isShowAgree: false
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
  // 回到原来的地方放
  app.navigateToLogin = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  
})